package com.example.myweixin;

import android.Manifest;
import android.app.Activity;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;

import android.app.FragmentManager;

import android.app.FragmentTransaction;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
//    weixinFragment mTab01;
//    frdFragment mTab02;
//    contactsFragment mTab03;
//    settingsFragment mTab04;
    private LinearLayout mTabWeiXin;
    private LinearLayout mTabFrd;
    private LinearLayout mTabContacts;
    private LinearLayout mTabSettings;

    private ImageButton mImgWeiXin;
    private ImageButton mImgFrd;
    private ImageButton mImgContacts;
    private ImageButton mImgSettings;

    private Fragment mTab01=new weixinFragment();
    private Fragment mTab02=new frdFragment();
    private Fragment mTab03=new contactsFragment();
    private Fragment mTab04=new settingsFragment();

    private FragmentManager fm;

    private FloatingActionButton mFloatingActionButton;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if(grantResults[0]!= PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this, "未授权，无法实现预定的功能！", Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else{
            initView();
            initFragment();
            initEvent();
            setSelect(0);  //初始值设置为0，默认weixinFragment为首页
        }

    }


    /**
     * 事件启动函数
     * 全屏监听太耗内存
     * 限制只监听4个LinearLayout
     */
    private void initEvent(){
        mTabWeiXin.setOnClickListener(this);
        mTabFrd.setOnClickListener(this);
        mTabContacts.setOnClickListener(this);
        mTabSettings.setOnClickListener(this);

    }

    private void initFragment(){
//        mTab01=new weixinFragment();
//        mTab02=new frdFragment();
//        mTab03=new contactsFragment();
//        mTab04=new settingsFragment();
        fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        transaction.add(R.id.id_content,mTab01);
        transaction.add(R.id.id_content,mTab02);
        transaction.add(R.id.id_content,mTab03);
        transaction.add(R.id.id_content,mTab04);
        transaction.commit();

    }

    private void initView(){
        mTabWeiXin=(LinearLayout)findViewById(R.id.id_tab_WeChat);
        mTabFrd=(LinearLayout)findViewById(R.id.id_tab_Frd);
        mTabContacts=(LinearLayout)findViewById(R.id.id_tab_Contacts);
        mTabSettings=(LinearLayout)findViewById(R.id.id_tab_Settings);

        mImgWeiXin=(ImageButton)findViewById(R.id.img_WeChat);
        mImgFrd=(ImageButton)findViewById(R.id.img_Frd);
        mImgContacts=(ImageButton)findViewById(R.id.img_Contacts);
        mImgSettings=(ImageButton)findViewById(R.id.img_Settings);
        mFloatingActionButton=(FloatingActionButton)findViewById(R.id.floatingActionButton);


    }

    private void setSelect(int i){
        FragmentTransaction transaction=fm.beginTransaction();
        hideFragment(transaction);
        //把图片设置为亮的
        //设置内容区域
        switch (i){
            case 0:
                Log.d("setSelect","1");
                transaction.show(mTab01);
                mImgWeiXin.setImageResource(R.drawable.tab_weixin_pressed);
                break;
            case 1:
                transaction.show(mTab02);
                mImgFrd.setImageResource(R.drawable.tab_find_frd_pressed);
                break;
            case 2:
                transaction.show(mTab03);
                mImgContacts.setImageResource(R.drawable.tab_address_pressed);
                break;
            case 3:
                transaction.show(mTab04);
                mImgSettings.setImageResource(R.drawable.tab_settings_pressed);
                break;
            default:break;
        }
        transaction.commit();
    }


    /**
     * 将4个fragment先全部隐藏
     */
    private void hideFragment(FragmentTransaction transaction){
        transaction.hide(mTab01);
        transaction.hide(mTab02);
        transaction.hide(mTab03);
        transaction.hide(mTab04);

    }

    public void onClick(View v){
        resetImgs();
        switch (v.getId()){
            case R.id.id_tab_WeChat:
                setSelect(0);
                break;
            case R.id.id_tab_Frd:
                setSelect(1);
                break;
            case R.id.id_tab_Contacts:
                setSelect(2);
                break;
            case R.id.id_tab_Settings:
                setSelect(3);
                break;
            case R.id.floatingActionButton:
                mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "点击了悬浮图片", Toast.LENGTH_SHORT).show();
                        final View addDialog=getLayoutInflater().inflate(R.layout.add_contact,null);

                        new AlertDialog.Builder(MainActivity.this).setView(addDialog).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText mname=(EditText)addDialog.findViewById(R.id.name);
                                EditText mphone=(EditText)addDialog.findViewById(R.id.phone);
                                final String name=mname.getText().toString();
                                final String phone=mphone.getText().toString();
                                // 创建一个空的ContentValues
                                ContentValues values = new ContentValues();
                                // 向RawContacts.CONTENT_URI执行一个空值插入
                                // 目的是获取系统返回的rawContactId
                                Uri rawContactUri = getContentResolver().insert(
                                        ContactsContract.RawContacts.CONTENT_URI, values);
                                long rawContactId = ContentUris.parseId(rawContactUri);
                                values.clear();
                                values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
                                // 设置内容类型
                                values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                // 设置联系人名字
                                values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
                                // 向联系人URI添加联系人名字
                                getContentResolver().insert(ContactsContract
                                        .Data.CONTENT_URI, values);
                                values.clear();
                                values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
                                values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                // 设置联系人的电话号码
                                values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
                                // 设置电话类型
                                values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                // 向联系人电话号码URI添加电话号码
                                getContentResolver().insert(ContactsContract
                                        .Data.CONTENT_URI, values);
                                values.clear();

                                setSelect(2);
                                Toast.makeText(MainActivity.this, "联系人数据添加成功",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }).show();
                    }
                });
                break;
             default:
                 break;
        }

    }

    /**
     * 切换图片至暗色
     */
    public void resetImgs(){
        mImgWeiXin.setImageResource(R.drawable.tab_weixin_normal);
        mImgFrd.setImageResource(R.drawable.tab_find_frd_normal);
        mImgContacts.setImageResource(R.drawable.tab_address_normal);
        mImgSettings.setImageResource(R.drawable.tab_settings_normal);

    }
}
